package com.zhouzi.zhaoyang.service

import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.hardware.usb.UsbManager.ACTION_USB_DEVICE_ATTACHED
import android.hardware.usb.UsbManager.ACTION_USB_DEVICE_DETACHED
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.widget.Toast
import com.orhanobut.logger.Logger
import com.printer.command.EscCommand
import com.zhouzi.zhaoyang.base.App
import com.zhouzi.zhaoyang.print.DeviceConnFactoryManager
import com.zhouzi.zhaoyang.print.DeviceConnFactoryManager.CONN_STATE_FAILED
import com.zhouzi.zhaoyang.print.PrinterCommand
import com.zhouzi.zhaoyang.print.ThreadPool
import java.util.*

/**
 * Created by ZhouZi on 2019/10/23.
 * time:9:37
 * ----------Dragon be here!----------/
 * 　　　┏┓　　 ┏┓
 * 　　┏┛┻━━━┛┻┓━━━
 * 　　┃　　　　　 ┃
 * 　　┃　　　━　  ┃
 * 　　┃　┳┛　┗┳
 * 　　┃　　　　　 ┃
 * 　　┃　　　┻　  ┃
 * 　　┃　　　　   ┃
 * 　　┗━┓　　　┏━┛Code is far away from bug with the animal protecting
 * 　　　　┃　　　┃    神兽保佑,代码无bug
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛━━━━━
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━━━━━━神兽出没━━━━━━━━━━━━━━
 */
class PrintService : Service() {

    companion object {
        val CONNECT_DEVICE = 0
        val PRINT = 1
    }

    private var usbManager: UsbManager? = null
    private var id = 0
    private var threadPool: ThreadPool? = null

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        if (intent != null) {
            val status = intent.getIntExtra("status", -1)
            when (status) {
                CONNECT_DEVICE -> {
                    closeport()
                    val usbDevice = intent.getParcelableExtra<UsbDevice>("usbDevice")
                    usbConn(usbDevice)
                }
                PRINT -> {
                    printOrder(sendReceiptWithResponse())
                }
            }
        }

        return super.onStartCommand(intent, flags, startId)
    }

    override fun onCreate() {
        super.onCreate()
        registerReceiver()
    }

    private fun registerReceiver() {
        val intentFliter = IntentFilter()
        intentFliter.addAction(ACTION_USB_DEVICE_DETACHED)
        intentFliter.addAction(ACTION_USB_DEVICE_ATTACHED)
        intentFliter.addAction(DeviceConnFactoryManager.ACTION_CONN_STATE)
        registerReceiver(receiver, intentFliter)
    }

    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            when (action) {
                ACTION_USB_DEVICE_DETACHED -> {
                    Logger.d("USB已断开")
                }
                ACTION_USB_DEVICE_ATTACHED -> {
                    Logger.d("USB已连接")
                }
                DeviceConnFactoryManager.ACTION_CONN_STATE -> {
                    val state = intent.getIntExtra(DeviceConnFactoryManager.STATE, -1)
                    val deviceId = intent.getIntExtra(DeviceConnFactoryManager.DEVICE_ID, -1)
                    val voiceIntent = Intent(this@PrintService, VoiceService::class.java)
                    when (state) {
                        DeviceConnFactoryManager.CONN_STATE_DISCONNECT -> {
                            Logger.d("CONN_STATE_DISCONNECT")
                            voiceIntent.putExtra("voiceStr", "打印机已断开连接")
                        }
                        DeviceConnFactoryManager.CONN_STATE_CONNECTING -> {
                            Logger.d("CONN_STATE_CONNECTING")
//                            voiceIntent.putExtra("voiceStr", "打印机连接成功")
                        }
                        DeviceConnFactoryManager.CONN_STATE_CONNECTED -> {
                            Logger.d("CONN_STATE_CONNECTED")
                            voiceIntent.putExtra("voiceStr", "打印机连接成功")
                        }
                        CONN_STATE_FAILED -> {
                            Logger.d("CONN_STATE_FAILED")
                            voiceIntent.putExtra("voiceStr", "打印机连接失败")
                        }
                    }
                    startService(voiceIntent)
                }
            }
        }
    }

    /**
     * usb连接
     *
     * @param usbDevice
     */
    private fun usbConn(usbDevice: UsbDevice) {
        DeviceConnFactoryManager.Build()
            .setId(id)
            .setConnMethod(DeviceConnFactoryManager.CONN_METHOD.USB)
            .setUsbDevice(usbDevice)
            .setContext(this)
            .build()
        DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].openPort()
    }

    /**
     * 重新连接回收上次连接的对象，避免内存泄漏
     */
    private fun closeport() {
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] != null && DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort != null) {
//            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].reader.cancel()
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort.closePort()
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort = null
        }
    }

    private fun printOrder(datas: Vector<Byte>) {
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] == null || !DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].connState) {
            return
        }
        threadPool = ThreadPool.getInstantiation()
        threadPool?.addTask {
            if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].currentPrinterCommand == PrinterCommand.ESC) {
                /* 发送数据 */
                DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(
                    datas
                )
            } else {
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(App.mContext, "打印错误", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        DeviceConnFactoryManager.closeAllPort()
        if (threadPool != null) {
            threadPool?.stopThreadPool()
            threadPool = null
        }
    }

    /**
     * 发送票据
     */
    private fun sendReceiptWithResponse(): Vector<Byte> {
        val esc = EscCommand()
        esc.addInitializePrinter()
        esc.addPrintAndFeedLines(3.toByte())
        /* 设置打印居中 */
        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER)
        esc.addText("商户名称\n")
        esc.addText("门店名称\n")
        esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT)
        esc.addText("支付方式：XXX\n")
        esc.addText("订单状态：XXX\n")
        esc.addText("交易金额：XXX\n")
        esc.addText("支付时间：XXX\n")
        esc.addText("订单号：XXX\n")
        esc.addText("员工编号：XXX\n")
        esc.addText("员工名称：XXX\n")
        esc.addText("设备ID：XXX\n")
        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER)
        esc.addText("服务商名称")
        esc.addPrintAndFeedLines(8.toByte())

        /* 加入查询打印机状态，用于连续打印 */
        val bytes = byteArrayOf(29, 114, 1)
        esc.addUserCommand(bytes)
        return esc.command
    }

}